package fr.unice.polytech.chord.samples.commands;

import java.util.Map;
import java.util.TreeMap;

import org.objectweb.proactive.api.PAFuture;

import fr.unice.polytech.chord.core.ChordNode;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.core.Tracker;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 11/09/2009
 */
public class ListNodesCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public ListNodesCommand(Manager manager) {
		super(manager, "List nodes on the current overlay", new String[] {
				"list", "ll", "ls" }, null);
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		Map<Key, String> orderedNodes = new TreeMap<Key, String>();

		ChordNode node = (ChordNode) PAFuture.getFutureValue(super.getManager()
				.getTracker().getRandomPeer());
		ChordNode currentNode = node;

		if (node == null) {
			System.out.println("Overlay contains 0 node");
		} else {
			try {
				orderedNodes.put(node.getKey(), node.toString());

				while (!(currentNode = currentNode.getSuccessor()).equals(node)) {
					orderedNodes.put(currentNode.getKey(), currentNode
							.toString());
				}

				System.out.println("Overlay currently contains :");
				for (String nodeInfo : orderedNodes.values()) {
					System.out.println("  - " + nodeInfo);
				}
			} catch (Exception e) {
				// a node has left or is dead, try again...
				try {
					Thread.sleep(Tracker.CHECK_INTERVAL_TIME);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				this.execute(args);
			}
		}
	}
}
